X
An express.js method that downloads the file at the path specified as an attachment. It takes these arguments.
Path - string, the path to the file you want to download.
Filename - string, the file name you want to call the file, if absent will use the filename in the path.
Options - object, an object used to specify options.
Callback - function, a function to do when it completes successfully or throws an error.
Here I'm going to make a html document with 2 buttons in it.
When I click the first button I'll reroute the browser with window.location.href to the "/download" route on the express server.
On the server, I'll make a get request to the "/download" route. In the response, I'll use the res.download() method with the path, filename & callback functions specified. When it comes back successful, I'll console.log() a message. The file will be downloaded when I hit this route. Also, the browser will remain on the same view or page even since res.end() was called instead of res.render() or res.redirect.
When res.download() completes successfully it automatically calls res.end() after the callback function. That means you don't need to call res.end(), res.json() or any other method that ends the response. Doing so will throw an error.
When calling a method that ends res.download(), you will receive a headers already sent error. This means that res.end() was called twice. To check for this, you could see if res.headersSent property is true. This property checks to see if a response was already sent.
The other error that will be thrown is if the path to file is wrong or the file being downloaded does not exist. If this happens you'll want to send a response status saying the file is not found.
If you need to use fetch to send some form info or do something else, you will have to make a middleman route an order to use res.download(). Res.download() will fire, but it will not download the file. I made a call to "/downloadImage" route, then returned a message. When the fetch request completes, I then reroute the browser to the "/download" route to get the file.
The express docs for res.download() says that browsers will prompt the user for download. I have not run into this myself. Here is code putting res.download() into action.